#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDoubleValidator>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QList<QSerialPortInfo> portInfos=QSerialPortInfo::availablePorts();
    ui->com->clear();
    foreach(QSerialPortInfo portInfo,portInfos)
    {
        QString portName=portInfo.portName();
        if(portInfo.isBusy())
        {
            ui->com->addItem(portName+"(使用中)");
        }
        else
        {
            ui->com->addItem(portName);
        }
    }

    connect(&serialPort,&QSerialPort::readyRead,this,&MainWindow::readMsg);
    std::time_t t=time(0);
    char temp[32]={NULL};
    strftime(temp,sizeof(temp),"%Y-%m-%d-%H_%M_%S-",localtime(&t));
    QString time=QString::fromUtf8(temp);
    QString filePath=time+"data.csv";
    qDebug()<<"filepath:"<<filePath;
    dataFile.setFileName(filePath);
    if(!dataFile.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        qDebug()<<"无法打开文件";
    }
    out.setDevice(&dataFile);
    out<<"head,status,pitch,roll,yaw,latitude,Wx,Wy,Wz,Ax,Ay,Az,temperature,id,check,tail\n";
}

MainWindow::~MainWindow()
{
    delete ui;
}


//请求反馈数据（设定下为系统周期上传）
void MainWindow::readMsg()
{
    /*⚠注意：串口得到的data实际上是字符的ascii码数组⚠*/
    QByteArray rawData=serialPort.readAll().toHex().left(47*2);
//    QByteArray rawData="5A A5 00 47 43 95 C2 87 A8 6C BD 00 00 00 00 E3 A5 1F 42 00 9C 9E 3A 06 90 77 BB C6 B5 A3 BA 88 19 17 3D CF 37 17 C1 14 C8 26 40 14 8E 0B 55 5A A5 00 47 43 95 C2 87 A8 6C BD 00 00 00 00 E3 A5 1F 42 A6 B7 A4 3A 88 A6 82 BB A6 5A 89 BA 5D 2E 19 3D 88 36 17 C1 B1 DE 26 40 14 8F 4C 55 5A A5 00 A2 41 95 C2 B4 C1 6B BD 00 00 00 00 E3 A5 1F 42 5E 54 9E 3A 2C 38 68 BB 9E 5B 3F BB AC 76 1A 3D C8 37 17 C1 E0 DB 26 40 14 90 29 55 5A A5 00 A2 41 95 C2 B4 C1 6B BD 00 00 00 00 E3 A5 1F 42 A2 EB A6 3A D5 7D 69 BB 1C F2 1E BB E8 EC 18 3D 5B 39 17 C1 44 CC 26 40 14 91 16 55 5A A5 00 84 45 95 C2 2E 35 6E BD 00 00 00 00 E3 A5 1F 42 FA 9F A0 3A 19 0F 4D BB A9 15 A3 BA 43 FB 18 3D 14 37 17 C1 E6 CA 26 40 14 92 5B 55";
    //test
//    qDebug()<<"串口数据："<<rawData.toHex();//这里输出的就是ascii码"35616135303035323430383663326635666438306266303030303030303065336135316634326539353838616261393831646439626163386334303333626662313265333365373037663130633137643762373234303161376439303535"

    int size=47*2;
//    QList<QByteArray> allFrames;

    for(int i=0;i+size<=rawData.size();i+=size)
    {
        QByteArray frame=rawData.mid(i,size);
        RECEIVE_FROM_INS receive_from_plc=deserializeFrame(rawData);

        ui->wx->display(receive_from_plc.Wx);
        ui->wy->display(receive_from_plc.Wy);
        ui->wz->display(receive_from_plc.Wz);
        ui->roll->display(receive_from_plc.roll);
        ui->pitch->display(receive_from_plc.pitch);
        ui->yaw->display(receive_from_plc.yaw);
        ui->latitude->display(receive_from_plc.latitude);

        ui->ax->display(receive_from_plc.Ax);
        ui->ay->display(receive_from_plc.Ay);
        ui->az->display(receive_from_plc.Az);

    }


        //判断字头和字尾
//    if(receive_from_plc.head!=0x66666666||receive_from_plc.tail!=0x88888888)
//    {
//        return;
//    }
//        qDebug()<<"receive:"<<data;
//    qDebug()<<"接收数据中";

    //ui->connected->setText("已连接");

    //接收数据,//状态字	=0 未启动；=1 初始化中；=2 初始化完成；=3 回零中；=4 已到零位；=5 负载定位中；=6 负载插入中；=7 负载安装到位；
    //			=8 平台退出中；=9急停；=10伺服故障；=11到极限位置指令无法下发；=12杆长到软限位;=13停止运动
//    if(receive_from_plc.status==1){
//        ui->status->setText("初始化中");
//    }
//    else if(receive_from_plc.status==2){
//        ui->status->setText("初始化完成");
//        //在这里判断是否连接成功合不合理？？？

//    }
//    else if(receive_from_plc.status==3){
//        ui->status->setText("回零中");
//    }
//    else if(receive_from_plc.status==4){
//        ui->status->setText("已回零");
//    }
//    else if(receive_from_plc.status==5){
//        ui->status->setText("定位中");
//    }
//    else if(receive_from_plc.status==6){
//        ui->status->setText("插入中");
//    }
//    else if(receive_from_plc.status==7){
//        ui->status->setText("安装到位");
//    }
//    else if(receive_from_plc.status==8){
//        ui->status->setText("推出中");
//    }
//    else if(receive_from_plc.status==9){
//        ui->status->setText("急停");
//    }
//    else if(receive_from_plc.status==10){
//        ui->status->setText("故障");
//    }
//    else if(receive_from_plc.status==11){
//        ui->status->setText("角度软极限");
//    }
//    else if(receive_from_plc.status==12){
//        ui->status->setText("杆长软限位");
//    }
//    else if(receive_from_plc.status==13){
//        ui->status->setText("停止运动");
//    }
//    else if(receive_from_plc.status==14){
//        ui->status->setText("硬限位");
//    }
//        ui->condition->display((int)receive_from_plc.status);

}

void MainWindow::on_com_connect_clicked()
{
    if(ui->com->currentText().mid(4,1)=="(")
    {
        //没办法保障此时的串口突然被连接后跳出提示
        QMessageBox::information(NULL,"错误提示！","请选择空闲的串口！",QMessageBox::Yes);
        return;
    }

    if(!isOpen)
    {
        isOpen=true;
        serialPort.setPortName(ui->com->currentText().trimmed());
        serialPort.setBaudRate(QSerialPort::Baud115200);
        serialPort.setParity(QSerialPort::NoParity);
        serialPort.setDataBits(QSerialPort::Data8);
        serialPort.setStopBits(QSerialPort::OneStop);

        if(serialPort.isOpen())
        {
            serialPort.clear();
            serialPort.close();
        }
        if(!serialPort.open(QIODevice::ReadWrite))
        {
            qDebug()<<serialPort.portName()<<"打开失败";
            return;
        }
    }
}

void MainWindow::on_com_disconnect_clicked()
{
//    QByteArray rawData="5A A5 00 47 43 95 C2 87 A8 6C BD 00 00 00 00 E3 A5 1F 42 00 9C 9E 3A 06 90 77 BB C6 B5 A3 BA 88 19 17 3D CF 37 17 C1 14 C8 26 40 14 8E 0B 55 5A A5 00 47 43 95 C2 87 A8 6C BD 00 00 00 00 E3 A5 1F 42 A6 B7 A4 3A 88 A6 82 BB A6 5A 89 BA 5D 2E 19 3D 88 36 17 C1 B1 DE 26 40 14 8F 4C 55 5A A5 00 A2 41 95 C2 B4 C1 6B BD 00 00 00 00 E3 A5 1F 42 5E 54 9E 3A 2C 38 68 BB 9E 5B 3F BB AC 76 1A 3D C8 37 17 C1 E0 DB 26 40 14 90 29 55 5A A5 00 A2 41 95 C2 B4 C1 6B BD 00 00 00 00 E3 A5 1F 42 A2 EB A6 3A D5 7D 69 BB 1C F2 1E BB E8 EC 18 3D 5B 39 17 C1 44 CC 26 40 14 91 16 55 5A A5 00 84 45 95 C2 2E 35 6E BD 00 00 00 00 E3 A5 1F 42 FA 9F A0 3A 19 0F 4D BB A9 15 A3 BA 43 FB 18 3D 14 37 17 C1 E6 CA 26 40 14 92 5B 55";
    QByteArray rawData="5aa500aebcabc20f73793e00000000e3a51f42009d35bbc71136bb4008e93af80614bf676b1cc1d49a033f1e751555";
    rawData.replace(" ","");
    qDebug()<<"串口数据："<<rawData;
    //test



    RECEIVE_FROM_INS receive_from_plc=deserializeFrame(rawData);

    qDebug()<<"tail:"<<receive_from_plc.tail;
    //ui->connected->setText("已连接");
//        ui->condition->display((int)receive_from_plc.status);
        ui->wx->display(receive_from_plc.Wx);
        ui->wy->display(receive_from_plc.Wy);
        ui->wz->display(receive_from_plc.Wz);
        ui->roll->display(receive_from_plc.roll);
        ui->pitch->display(receive_from_plc.pitch);
        ui->yaw->display(receive_from_plc.yaw);
        ui->latitude->display(receive_from_plc.latitude);

        ui->ax->display(receive_from_plc.Ax);
        ui->ay->display(receive_from_plc.Ay);
        ui->az->display(receive_from_plc.Az);

}

//QByteArray MainWindow::serializeFrame(SEND_TO_PLC frame)
//{
//    QByteArray data;
//    QDataStream stream(&data, QIODevice::WriteOnly);
////    QDataStream::setFloatingPointPrecision(QDataStream::SinglePrecision);

//    stream.setByteOrder(QDataStream::BigEndian);
//    stream<<frame.head<<frame.count<<
//            frame.command<<frame.subCommand<<frame.subCommand2;
//    //QDataStream默认浮点型数据为8字节
//    writeReal(stream,frame.x);
//    writeReal(stream,frame.y);
//    writeReal(stream,frame.z);
//    writeReal(stream,frame.roll);
//    writeReal(stream,frame.yaw);
//    writeReal(stream,frame.pitch);
//    stream<<frame.tail;
//            //frame.max_v<<frame.max_omega<<frame.max_a<<frame.max_beta<<
//    return data;
//}


//void MainWindow::writeReal(QDataStream& out, float f)
//{
//    out.setFloatingPointPrecision(QDataStream::SinglePrecision);
//    out << f;
//}




